#include <iostream>
#include <algorithm>
#include <cstring>
#include <vector>
#include <string>


using namespace std;
using LL = long long;
const int N = 4e4 + 10, INF = 1e8;

struct Node
{
    int l, r;
    int key, val;
}node[N];

int n;
int root, idx;
int A[N];

int get_node(int key){
    idx ++;
    node[idx].key = key;
    node[idx].val = rand();
    return idx;
}

void zig(int &p){
    int q = node[p].l;
    node[p].l = node[q].r;
    node[q].r = p;
    p = q;
}//右旋


void zag(int &p){
    int q = node[p].r;
    node[p].r = node[q].l;
    node[q].l = p;
    p = q;
}//左旋

void build(){
    get_node(-INF), get_node(INF);
    root = 1;
    node[root].r = 2;

    if(node[root].val < node[2].val) zag(root);
}

void insert(int &p, int key){
    if(!p){
        p = get_node(key);
    }else{
        if(node[p].key == key){
            return;
        }else if(node[p].key > key){
            insert(node[p].l, key);
            if(node[node[p].l].val > node[p].val) zig(p);
        }else{
            insert(node[p].r, key);
            if(node[node[p].r].val > node[p].val) zag(p);
        }
    }
}


int get_min(int p, int key){
    if(!p) return -INF;

    if(node[p].key > key){
        return get_min(node[p].l, key);
    }

    return max(node[p].key, get_min(node[p].r, key));
}

int get_max(int p, int key){
    if(!p) return INF;

    if(node[p].key < key){
        return get_max(node[p].r, key);
    }

    return min(node[p].key, get_max(node[p].l, key));
}


int main(){
    freopen("in.txt", "r", stdin);
    freopen("out.txt", "w", stdout);

    build();

    scanf("%d", &n);

    for(int i = 1; i <= n; i ++) scanf("%d", &A[i]);

    LL res = 0;
    res = A[1];
    insert(root, A[1]);
    int a1, a2;
    for(int i = 2; i <= n; i ++){
        a1 = get_min(root, A[i]);
        a2 = get_max(root, A[i]);

        int temp = min(abs(A[i] - a1), abs(A[i] - a2));
        res = (LL) res + temp;
        insert(root, A[i]);
    }

    printf("%lld\n", res);

    return 0;
}
